package com.uwo.house.util;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by PHS on 2017/9/25.
 */
@Controller
@RequestMapping("/exportExcel")
public class ExportExcel {
    @RequestMapping( value = "/excelOut")
    public void excelStandardTemplateOut(HttpServletRequest request,
                                         HttpServletResponse response) throws IOException {
        /*URL save = Thread.currentThread().getContextClassLoader().getResource("");
        String str = save.toString();
        str=str.substring(6,str.length());
        str=str.replaceAll("%20", " ");
        int num = str.lastIndexOf("uwo-house");//项目名，应用到不同的项目中，这个需要修改！
        str=str.substring(0, num+"uwo-house".length());
        str = str +"/demo/材料清单模板.xlsx";//Excel模板所在的路径。*/
        //String str = "http://120.27.151.238:8080/uwo-house/attachments/materialTemplate.xlsx";
        String str = "http://122.237.100.110:80/uwo-house/attachments/materialTemplate.xlsx";
        URL url = new URL(str);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(("材料清单模板" + ".xlsx").getBytes(), "iso-8859-1"));//下载文件的名称
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            URLConnection conn = url.openConnection();
            bis = new BufferedInputStream(conn.getInputStream());
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
    }
}
